import React from 'react';
import { eventTrack } from '@/utils/track';
import { Divider, Table, Popconfirm, message, Typography, Tooltip } from 'antd';
import { Link, router } from 'umi';
import { deleteJob, deleteJobCheck } from '@/services/organization';
import Pagination from '@/components/Pagination';
import authHelper from '@/utils/auth/helper';
import { hasWorkFlowByType } from '@/pages/WorkFlow/utils';
import IconFont from '@/components/IconFont';
import { newTabProps } from '@/utils/tab';

import { useJobList } from '../../hooks';

const { checkCode } = authHelper;
export default ({ query, setQuery }) => {
    const getDefaultSortOrder = field => {
        if (query.orderByField) {
            const arr = query.orderByField.split('|');
            const targetField = arr[0];
            if (targetField && field === targetField) {
                return `${arr[1]}end`;
            }
        }
        return undefined;
    };
    const [loading, data, total] = useJobList(query);

    const columns = [
        {
            title: '职位类别',
            dataIndex: 'positionTypeName',
            sorter: true,
            defaultSortOrder: getDefaultSortOrder('positionTypeName'),
            key: 'positionTypeName',
            render: (_, record) => {
                const { firstPositionCodeName, secondPositionCodeName } = record;
                return [firstPositionCodeName, secondPositionCodeName].join('-');
            }
        },
        {
            title: '职位名称',
            sorter: true,
            defaultSortOrder: getDefaultSortOrder('positionName'),
            dataIndex: 'positionName',
            key: 'positionName'
        },
        {
            title: '职级',
            sorter: true,
            defaultSortOrder: getDefaultSortOrder('rankValue'),
            dataIndex: 'rankValue',
            key: 'rankValue'
        },
        {
            title: '员工数',
            sorter: true,
            defaultSortOrder: getDefaultSortOrder('employeeNumber'),
            dataIndex: 'employeeNumber',
            key: 'employeeNumber',
            render: (text, record) => {
                if (!text) return '-';
                return checkCode('office:orgs:post:emlist') ? (
                    <Typography.Text style={{ marginBottom: 0 }} title="在职员工数，点击可以打开员工管理">
                        <Link
                            onClick={() => {
                                // 埋点
                                eventTrack({
                                    eventName: 'organization_job_staff_click',
                                    eventProps: { post_name: record.positionName }
                                });
                            }}
                            to={{
                                pathname: '/office/personnelManagement/organization/employeeList',
                                query: {
                                    positionCodes: [record.positionCode]
                                    // positionName: record.positionName,
                                    // serviceStatus: [1, 2, 3, 4, 5, 7]
                                },
                                state: { tabRoute: true, tabRefresh: true }
                            }}
                        >
                            {/* {text} */}
                            {text}
                        </Link>
                    </Typography.Text>
                ) : (
                    text
                );
            }
        },
        {
            title: '创建时间',
            defaultSortOrder: getDefaultSortOrder('createTime'),
            sorter: true,
            dataIndex: 'createTime',
            key: 'createTime'
        },
        {
            title: '操作',
            dataIndex: 'address',
            key: 'address',
            render(_, record) {
                return (
                    <>
                        <Tooltip title="查看详情">
                            <IconFont
                                isButton
                                icon="iconlistfunction_view_icon_default"
                                style={{ fontSize: '24px' }}
                                onClick={() => {
                                    // 埋点
                                    eventTrack({
                                        eventName: 'organization_job_detail_click',
                                        eventProps: { post_name: record.positionName }
                                    });
                                    history.push({
                                        pathname: '/office/personnelManagement/organization/job/edit',
                                        query: { positionCode: record.positionCode, action: 'detail' },
                                        ...newTabProps
                                    });
                                }}
                                disabled={!checkCode('office:orgs:post:detail')}
                            />
                        </Tooltip>

                        <Divider type="vertical" />
                        <Tooltip title="编辑">
                            <IconFont
                                icon="iconlistfunction_edit_icon_default"
                                style={{ fontSize: '24px' }}
                                isButton
                                onClick={() => {
                                    eventTrack({
                                        eventName: 'organization_job_edit_click',
                                        eventProps: { post_name: record.positionName }
                                    });
                                    history.push({
                                        pathname: '/office/personnelManagement/organization/job/edit',
                                        query: { positionCode: record.positionCode, action: 'edit' }
                                    });
                                }}
                                disabled={!checkCode('office:orgs:post:edit')}
                            />
                        </Tooltip>
                        <Divider type="vertical" />
                        <Popconfirm
                            title="你确定删除吗?"
                            onConfirm={async () => {
                                const { msg: delCheckMsg, code: delCheckCode } = await deleteJobCheck(
                                    record.positionCode
                                );
                                if (delCheckCode === 10000) {
                                    // 校验流程是否存在
                                    const { workFlowUrl } = await hasWorkFlowByType('PostApply');
                                    if (workFlowUrl) {
                                        // 流程存在添加到历史记录
                                        const { msg, code, data: id } = await deleteJob({
                                            positionCode: record.positionCode,
                                            operationType: 2 // operationType是数字，保存是0，编辑是1， 删除是2
                                        });
                                        if (code === 10000) {
                                            await eventTrack({
                                                eventName: 'organization_job_delete_submit_click',
                                                eventProps: { post_name: record.positionName, status: 0 }
                                            });
                                            history.push(`${workFlowUrl}${id}&bId=${id}`); // 警告！！参数bId是职位套件专用，后面套件没用这个东西！！无奈
                                        } else {
                                            eventTrack({
                                                eventName: 'organization_job_delete_submit_click',
                                                eventProps: {
                                                    post_name: record.positionName,
                                                    status: 1,
                                                    error_info: msg
                                                }
                                            });
                                            message.error(msg);
                                        }
                                    }
                                } else {
                                    message.error(delCheckMsg);
                                }
                            }}
                            onCancel={() => {
                                eventTrack({
                                    eventName: 'organization_job_delete_cancel_click',
                                    eventProps: { post_name: record.positionName }
                                });
                            }}
                            okText="确定"
                            cancelText="取消"
                        >
                            <Tooltip title="删除">
                                <IconFont
                                    icon="iconlistfunction_delete_icon_default"
                                    style={{ fontSize: '24px' }}
                                    isButton
                                    onClick={() => {
                                        eventTrack({
                                            eventName: 'organization_job_delete_click',
                                            eventProps: { post_name: record.positionName }
                                        });
                                    }}
                                    disabled={!checkCode('office:orgs:post:delete')}
                                />
                            </Tooltip>
                        </Popconfirm>
                    </>
                );
            }
        }
    ];

    const handleTableChange = (pagination, filters, sorter) => {
        let orderByField = '';
        if (sorter.order) {
            const map = {
                ascend: 'asc',
                descend: 'desc'
            };
            orderByField = `${sorter.field}|${map[sorter.order]}`;
        }
        setQuery({ ...query, orderByField, current: 1 });
    };

    return (
        <>
            <Table
                rowKey="positionCode"
                dataSource={data}
                columns={columns}
                onChange={handleTableChange}
                loading={loading}
                pagination={false}
            />
            <Pagination total={total} {...query} onChange={page => setQuery({ ...query, ...page })} />
        </>
    );
};
